package com.gome.axwl.aoc.service.impl;

import com.gome.axwl.aoc.common.util.BeanJsonUtil;
import com.gome.axwl.aoc.common.util.DateUtil;
import com.gome.axwl.aoc.dao.GradeRuleDao;
import com.gome.axwl.aoc.entity.dto.GradeRuleDto;
import com.gome.axwl.aoc.entity.dto.GradeRuleParamDto;
import com.gome.axwl.aoc.entity.dto.QueryResultAndModifyStatusDto;
import com.gome.axwl.aoc.entity.po.GradeRulePo;
import com.gome.axwl.aoc.entity.po.IntegrationRulePo;
import com.gome.axwl.aoc.service.GradeRuleService;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import com.gome.datasource.shard.annotation.ReadDatasource;
import com.gome.datasource.shard.annotation.WriteDatasource;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Auther: yinyuxin@gome.com.cn
 * @Date: 2018/4/27 11:54
 */
@Service("gradeRuleService")
public class GradeRuleServiceImpl implements GradeRuleService {

    @Autowired
    private GradeRuleDao gradeRuleDao;

    private static final Logger LOGGER=LoggerFactory.getLogger(GradeRuleServiceImpl.class);

    @Override
    @ReadDatasource
    public ResultData<QueryResultAndModifyStatusDto<GradeRuleDto>> queryGradeRules(String date) {
        if(null==date || "".equals(date)){
            date=DateUtil.date2String(new Date(),DateUtil.FORMAT_DATE_WITHOUT_DAY);
        }
        QueryResultAndModifyStatusDto<GradeRuleDto> data=new QueryResultAndModifyStatusDto<>();
        GradeRulePo gradeRuleParamPo=new GradeRulePo();
        gradeRuleParamPo.setGradeDate(date);
        List<GradeRulePo> gradeRulePoList = null;
        try {
            gradeRulePoList = gradeRuleDao.queryByList(gradeRuleParamPo);
        } catch (Exception e) {
            LOGGER.error("查询等级规则信息失败，查询条件：{}，异常信息：{}", "date:"+date, ExceptionUtils.getFullStackTrace(e));
            return new ResultData(ErrorCode.QUERY_FAILOR,ErrorCode.QUERY_FAILOR_MSG);
        }
        List<GradeRuleDto> gradeRueDtos=BeanJsonUtil.listConvert(gradeRulePoList,GradeRuleDto.class);
        if (!CollectionUtils.isEmpty(gradeRueDtos)){
            //判断是否支持修改
            GradeRuleDto gradeRueDto=gradeRueDtos.get(0);
            data.setModify(this.checkModifyStatus(gradeRueDto.getGradeDate()));
        }
        data.setData(gradeRueDtos);
        return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,data);
    }

    @Override
    @WriteDatasource
    @Transactional(rollbackFor = Exception.class)
    public ResultData modifyGradeRules(GradeRuleParamDto gradeRuleParamDto) {
        //1：判断前端所传日期是否支持修改
        if (!this.checkModifyStatus(gradeRuleParamDto.getDate())){
            return new ResultData(ErrorCode.UPDATE_FAILOR,"数据不支持修改");
        }
        //2: 批量删除已有的积分规则
        gradeRuleDao.batchDeleteByDate(gradeRuleParamDto.getDate());
        //3: 批量新增
        List<GradeRuleDto> gradeRuleDtoParams = gradeRuleParamDto.getGradeRules();
        if (CollectionUtils.isEmpty(gradeRuleDtoParams)){
            return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        }
        for (GradeRuleDto gradeRuleDto:gradeRuleDtoParams){
            gradeRuleDto.setCreateTime(new Date());
            gradeRuleDto.setGradeDate(gradeRuleParamDto.getDate());
            gradeRuleDto.setCreateUserCode(gradeRuleParamDto.getModifyUserCode());
        }
        List<GradeRulePo> gradeRulePoList=BeanJsonUtil.listConvert(gradeRuleDtoParams,GradeRulePo.class);
        gradeRuleDao.batchInsert(gradeRulePoList);
        return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
    }

    @Override
    @ReadDatasource
    public ResultData<List<GradeRuleDto>> queryGradeValuesByMonth(String gradeDate) {
        if(null==gradeDate || "".equals(gradeDate)){
            gradeDate=DateUtil.date2String(new Date(),DateUtil.FORMAT_DATE_WITHOUT_DAY);
        }
        try {
            List<GradeRulePo> gradeRulePos=gradeRuleDao.queryGradeValuesByMonth(gradeDate);
            List<GradeRuleDto> gradeRuleDtos=BeanJsonUtil.listConvert(gradeRulePos,GradeRuleDto.class);
            return new ResultData<>(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG,gradeRuleDtos);
        } catch (Exception e) {
            LOGGER.error("查询等级值清单出现异常{}", ExceptionUtils.getFullStackTrace(e));
            return new ResultData(ErrorCode.QUERY_FAILOR,ErrorCode.QUERY_FAILOR_MSG);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @WriteDatasource
    public ResultData initGradeRules() {
        //0：校验当月是否已有数据
        String lastMonthDate=DateUtil.date2String(DateUtil.timeCalculation(new Date(),-1,1),DateUtil.FORMAT_DATE_WITHOUT_DAY);
        String nowDate=DateUtil.date2String(new Date(),DateUtil.FORMAT_DATE_WITHOUT_DAY);
        GradeRulePo gradeRulePo=new GradeRulePo();
        gradeRulePo.setGradeDate(nowDate);
        List<GradeRulePo> gradeRulePosNow = gradeRuleDao.queryByList(gradeRulePo);
        if (gradeRulePosNow!=null && gradeRulePosNow.size()>0){
            LOGGER.info("当月已有等级规则记录，跳过自动初始化");
            return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
        }
        //1：获取上个月的整套积分规则信息
        gradeRulePo.setGradeDate(lastMonthDate);
        List<GradeRulePo> gradeRulePosLast = gradeRuleDao.queryByList(gradeRulePo);
        if (CollectionUtils.isEmpty(gradeRulePosLast)){
            throw new RuntimeException("获取上个月等级规则信息为null,请检查原因");
        }
        //去掉id ，修改相关参数。用于当前月的初始化数据
        for (GradeRulePo gradeRulePo1:gradeRulePosLast){
            gradeRulePo1.setId(null);
            gradeRulePo1.setGradeDate(nowDate);
            gradeRulePo1.setCreateTime(new Date());
            gradeRulePo1.setCreateUserCode("system");
        }
        //批量增加
        gradeRuleDao.batchInsert(gradeRulePosLast);
        return new ResultData(ErrorCode.SUCCESS,ErrorCode.SUCCESS_MSG);
    }

    /**
     * 校验数据是否满足修改条件
     * @param dateString
     * @return
     */
    public Boolean checkModifyStatus(String dateString) {
        try {
            int nowYear = new DateTime(new Date()).getYear();
            int dataYear = new DateTime(DateUtil.string2Date(dateString, DateUtil.FORMAT_DATE_WITHOUT_DAY)).getYear();
            if (nowYear != dataYear) {
                return false;
            } else {
                int nowMonth = new DateTime(new Date()).getMonthOfYear();
                int dataMonth = new DateTime(DateUtil.string2Date(dateString, DateUtil.FORMAT_DATE_WITHOUT_DAY)).getMonthOfYear();
                return nowMonth == dataMonth ? true : false;
            }
        } catch (Exception e) {
            LOGGER.error("判断数据是否满足修改条件时出现异常{}", ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }
}
